package com.ssm.utils;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletOutputStream;

import com.ssm.entity.UserVo;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import sun.invoke.empty.Empty;

public class  ExcelExport{

    public void export(String[] titles, ServletOutputStream out, List<UserVo> data) throws Exception{
        try{
            // 第一步，创建一个workbook，对应一个Excel文件
            HSSFWorkbook workbook = new HSSFWorkbook();

            // 第二步，在webbook中添加一个sheet,对应Excel文件中的sheet
            HSSFSheet hssfSheet = workbook.createSheet("sheet1");

            // 第三步，在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short

            HSSFRow row = hssfSheet.createRow(0);
            // 第四步，创建单元格，并设置值表头 设置表头居中
            HSSFCellStyle hssfCellStyle = workbook.createCellStyle();

            //居中样式
            hssfCellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);

            HSSFCell hssfCell = null;
            for (int i = 0; i < titles.length; i++) {
                hssfCell = row.createCell(i);//列索引从0开始
                hssfCell.setCellValue(titles[i]);//列名1
                hssfCell.setCellStyle(hssfCellStyle);//列居中显示
            }

            // 第五步，写入实体数据

            for (int i = 0; i < data.size(); i++) {
                row = hssfSheet.createRow(i+1);
                UserVo userVo = data.get(i);

                // 第六步，创建单元格，并设置值
                Long  id = null;
                if(userVo.getUserId() >= 0){
                    id = userVo.getUserId();
                }
                row.createCell(0).setCellValue(id);
                String name = "";
                if(userVo.getUsername() != null){
                    name = userVo.getUsername();
                }
                row.createCell(1).setCellValue(name);
                String password = "";
                if(userVo.getPassword() != null){
                    password = userVo.getPassword();
                }
                row.createCell(2).setCellValue(password);
                String age=null;
                if(userVo.getEmail() !=null){
                    age = userVo.getEmail();
                }
                row.createCell(3).setCellValue(age);
            }

            // 第七步，将文件输出到客户端浏览器
            try {
                workbook.write(out);
                out.flush();
                out.close();

            } catch (Exception e) {
                e.printStackTrace();
            }
        }catch(Exception e){
            e.printStackTrace();
            throw new Exception("导出信息失败！");

        }
    }
}